#include <gflags/gflags.h>
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

DEFINE_bool(g, false, "Load as gray-scale image");
DEFINE_bool(s, false, "Make the window scalable");

void decomposeFilePath(const string& filepath_full, string& filepath, string& filename, string& basename)
{
    int p1 = filepath_full.find_last_of('/');
    filepath = p1 < 0 ? "./" : filepath_full.substr(0, p1);
    filename = filepath_full.substr(p1 + 1);
    int p2 = filename.find_first_of('.');
    basename = filename.substr(0, p2);
}

int main(int argc, char** argv)
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    if (argc < 2) {
        cout << "Usage:\n"
             << "ImageView <image_name> [options]" << endl;
        return 1;
    }

    string fn_image = argv[1];
    Mat image = imread(fn_image);
    if (image.empty()) {
        cout << "Cannot load image " << fn_image << endl;
        return -1;
    }
    if (FLAGS_g)
        cvtColor(image, image, COLOR_BGR2GRAY);
    string filepath, filename, basename;
    decomposeFilePath(fn_image, filepath, filename, basename);

    int win_flag = WINDOW_AUTOSIZE;
    if (FLAGS_s)
        win_flag = WINDOW_NORMAL;
    string win_name = filename;
    namedWindow(win_name, win_flag);
    imshow(win_name, image);
    waitKey(0);

    return 0;
}